package service.Impl;

import entity.MsgXmlEntity;
import org.dom4j.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.IOException;
import java.io.StringWriter;
import java.net.URISyntaxException;
import java.util.*;

/**
 * Created by thinkjoy on 2017/8/30.
 * 所有微信返回的xml均由此解析
 */
@Service
public class WsParseXML {

    private Map<String,Object> result=new HashMap<>();

    @Autowired
    private WsBindingImpl wsBinding;

    @Autowired
    private WsUserImpl wsUser;

    /**
     * 处理微信返回的xml数据包
     * @param xml
     * @param response
     */
    public void getbasemsg(String xml, HttpServletResponse response) throws JAXBException, IOException, URISyntaxException {
        response.setCharacterEncoding("UTF-8");
        parseXML(xml);

        /**
         * 新用户首次关注收到自动回复消息
         */
        if (result.get("MsgType").toString().equals("event") && result.get("Event").toString().equals("subscribe")){
            String openid=result.get("FromUserName").toString();
            String ToUserName=result.get("ToUserName").toString();
            MsgXmlEntity msgXmlEntity=new MsgXmlEntity(openid,ToUserName, (int) (new Date().getTime()/1000),"text","欢迎使用芝麻智能前台，首次使用请先点击下方《- 考勤 -》登录");
            String document=DocumentXml(msgXmlEntity);
            response.getWriter().print(document);//自动回复
        }else if (result.get("MsgType").toString().equals("event") && result.get("Event").toString().equals("unsubscribe")){//取消关注
            String openid=result.get("FromUserName").toString();
            String dbopenid=wsUser.findOpenIdIsExit(openid);
            if (!StringUtils.isEmpty(dbopenid)){
                wsUser.deleteUserByOpenid(dbopenid);//取消关注时删除记录
            }
        }

        /**
         * 菜单操作
         */
        if(result.get("MsgType").toString().equals("event") && result.get("Event").toString().equals("VIEW")  ||
                result.get("MsgType").toString().equals("event") && result.get("Event").toString().equals("CLICK")){
            String openid=result.get("FromUserName").toString();
            wsBinding.setOpenid(openid);
        }

    }

    /**
     * 解析xml
     * @param xml
     */

    public void parseXML(String xml){
        try {
            if (!result.isEmpty()){
                result.clear();
            }
            Document doc=DocumentHelper.parseText(xml);
            Element root=doc.getRootElement();
            listNodes(root);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    public void listNodes(Element node){
        //首先获取当前节点的所有属性节点
        List<Attribute> list = node.attributes();
        //遍历属性节点
//        for(Attribute attribute : list){
//            System.out.println("属性"+attribute.getName() +":" + attribute.getValue());
//        }
        //如果当前节点内容不为空，则输出
        if(!(node.getTextTrim().equals(""))){
//            System.out.println( node.getName() + "：" + node.getText());
            result.put(node.getName(),node.getText());
        }
        //同时迭代当前节点下面的所有子节点
        //使用递归
        Iterator<Element> iterator = node.elementIterator();
        while(iterator.hasNext()){
            Element e = iterator.next();
            listNodes(e);
        }
    }

    /**
     * 对象转成xml
     */
    public String DocumentXml(MsgXmlEntity msgXmlEntity) throws JAXBException {
        JAXBContext jbt=JAXBContext.newInstance(MsgXmlEntity.class);
        StringWriter sw = new StringWriter();
        Marshaller ms=jbt.createMarshaller();
        ms.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);//设置格式
        ms.setProperty(Marshaller.JAXB_FRAGMENT, true);//去掉头部声明
        ms.marshal(msgXmlEntity,sw);
        return sw.toString();
    }
}
